package com.ja.openchat.ui.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogPrivacyInfo;
import com.zy.openchat.core.model.circle.BlogRuleInfo;
import com.zy.openchat.core.model.setting.UserPrivacySetting;
import com.zy.openchat.core.model.setting.UserPrivacySettingInfo;
import com.zy.openchat.core.model.setting.UserPrivacySettingRules;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PrivaicyAndPermissionActivity extends JaBaseActivity {

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PrivaicyAndPermissionActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.lastOnlineValueText)
    TextView lastOnlineValueText;
    @BindView(R.id.voiceValueText)
    TextView voiceValueText;
    @BindView(R.id.phoneValueText)
    TextView phoneValueText;
    @BindView(R.id.groupValueText)
    TextView groupValueText;
    @BindView(R.id.messageValueText)
    TextView messageValueText;
    @BindView(R.id.userNameSwitch)
    Switch userNameSwitch;
    @BindView(R.id.phoneSwitch)
    Switch phoneSwitch;
    @BindView(R.id.lookMeScopeText)
    TextView lookMeScopeText;
    @BindView(R.id.lookOtherScopeText)
    TextView lookOtherScopeText;


    public List<String> chooseLables1 = new ArrayList<>();
    public List<String> chooseLables2 = new ArrayList<>();
    public List<String> friendLookScope = new ArrayList<>();
    public List<String> strangerLookScope = new ArrayList<>();

    private final UserPrivacySetting[] userPriceSettings = new UserPrivacySetting[]{
            new UserPrivacySetting(UserPrivacySetting.ONLINE_STATUS),
            new UserPrivacySetting(UserPrivacySetting.VOICE_CALL),
            new UserPrivacySetting(UserPrivacySetting.SHOW_PHONE),
            new UserPrivacySetting(UserPrivacySetting.GROUP),
            new UserPrivacySetting(UserPrivacySetting.MESSAGE),
            new UserPrivacySetting(UserPrivacySetting.FIND_USERNAME,false),
            new UserPrivacySetting(UserPrivacySetting.FIND_PHONE,false)};

    private int[] chooseSettingIndex = {-1,-1,-1,-1,-1,0,0};
    private View[] settingLables;
    @Override
    public void initData() {
        chooseLables1.clear();
        chooseLables1.add(getString(R.string.everyone_text));
        chooseLables1.add(getString(R.string.home_contacts));
        chooseLables1.add(getString(R.string.nobody_text));
        setTitle(getString(R.string.privacy_and_permissions));
        chooseLables2.clear();
        chooseLables2.add(getString(R.string.everyone_text));
        chooseLables2.add(getString(R.string.home_contacts));
        friendLookScope.clear();
        friendLookScope.add(getString(R.string.last_3_days));
        friendLookScope.add(getString(R.string.last_month));
        friendLookScope.add(getString(R.string.last_half_year));
        friendLookScope.add(getString(R.string.last_year));
        strangerLookScope.clear();
        strangerLookScope.add(getString(R.string.piece_3_text));
        strangerLookScope.add(getString(R.string.piece_10_text));
        strangerLookScope.add(getString(R.string.all_text));
        settingLables = new View[]{lastOnlineValueText,voiceValueText,phoneValueText,groupValueText,messageValueText,userNameSwitch,phoneSwitch};
        for(int i =0;i<userPriceSettings.length;i++){
            UserPrivacySetting setting = userPriceSettings[i];
            final int position = i;
            TelegramManager.getTelegramManager().getUserPrivacySettingRules(this, setting, new TgResultBlock<UserPrivacySettingRules>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, UserPrivacySettingRules obj) {
                    if(obj!=null){
                        int index = obj.getRuleIndex();
                        if(setting.isChooseList){
                            chooseSettingIndex[position] = index;
                            ((TextView)settingLables[position]).setText(index!=-1?chooseLables1.get(index):getString(R.string.nobody_text));
                        }else{
                            chooseSettingIndex[position]=index==0?1:0;
                            ((Switch)settingLables[position]).setChecked(index==0);
                        }
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
        phoneSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingRule(6,phoneSwitch.isChecked()?0:2);
            }
        });
        userNameSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingRule(5,userNameSwitch.isChecked()?0:2);
            }
        });
        TelegramManager.getTelegramManager().getCircleAllPrivacy(this, new TgResultBlock<List<BlogPrivacyInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<BlogPrivacyInfo> obj) {
                resetCircleUI(obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void resetCircleUI(List<BlogPrivacyInfo> privacyInfos){
        if(!Common.isEmpty(privacyInfos)){
            for(BlogPrivacyInfo blogPrivacyInfo:privacyInfos){
                resetCircleUI(blogPrivacyInfo);
            }
        }
    }
    private int friendLookMeIndex = -1;
    private int strangerLookMeIndex = -1;
    private void resetCircleUI(BlogPrivacyInfo privacyInfos){
        if(privacyInfos.key == BlogPrivacyInfo.FRIEND_LOOK_ME_SCOPE){
            if(!Common.isEmpty(privacyInfos.rules)){
                BlogRuleInfo blogRuleInfo = privacyInfos.rules.get(0);
                if(blogRuleInfo.rule == BlogRuleInfo.RULE_OF_ALL){
                    friendLookMeIndex = 3;
                }else{
                    switch (blogRuleInfo.days){
                        case 3:
                            friendLookMeIndex = 0;
                            break;
                        case 30:
                            friendLookMeIndex = 1;
                            break;
                        case 180:
                            friendLookMeIndex = 2;
                            break;
                        default:
                            friendLookMeIndex = 3;
                            break;
                    }
                }

                lookMeScopeText.setText(friendLookScope.get(friendLookMeIndex));
            }
        }else if(privacyInfos.key == BlogPrivacyInfo.STRANGER_LOOK_ME_SCOPE){
            if(!Common.isEmpty(privacyInfos.rules)) {
                BlogRuleInfo blogRuleInfo = privacyInfos.rules.get(0);
                if(blogRuleInfo.rule == BlogRuleInfo.RULE_OF_ALL){
                    strangerLookMeIndex = 2;
                }else{
                    switch (blogRuleInfo.counts){
                        case 3:
                            strangerLookMeIndex = 0;
                            break;
                        case 10:
                            strangerLookMeIndex = 1;
                            break;
                        default:
                            strangerLookMeIndex = 2;
                            break;
                    }
                }
                lookOtherScopeText.setText(strangerLookScope.get(strangerLookMeIndex));
            }
        }
    }

    private void resetUI(UserPrivacySettingInfo settingInfo){
        if(settingInfo==null||settingInfo.setting==null|| settingInfo.rules==null){
            return;
        }
        for(int i =0;i<userPriceSettings.length;i++){
            UserPrivacySetting setting = userPriceSettings[i];
            if(setting.type.equals(settingInfo.setting.type)){
                int index = settingInfo.rules.getRuleIndex();
                if(setting.isChooseList){
                    chooseSettingIndex[i] = index;
                    ((TextView)settingLables[i]).setText(index!=-1?chooseLables1.get(index):getString(R.string.nobody_text));
                }else{
                    chooseSettingIndex[i]=index==0?1:0;
                    ((Switch)settingLables[i]).setChecked(index==0);
                }
                break;
            }
        }
    }

    private void circleSetting(BlogPrivacyInfo info){
        if(info==null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().setCircleAllPrivacy(this, info, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&!obj.ok){
                    ToastUtils.showShort(getString(R.string.request_error));
                }else{
                    resetCircleUI(info);
                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort(getString(R.string.request_error));
            }
        });
    }

    private void settingRule(int index,int chooseIndex){
        showProgress();
        TelegramManager.getTelegramManager().setUserPrivacySettingRules(this, userPriceSettings[index], new UserPrivacySettingRules(chooseIndex), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&!obj.ok){
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort(getString(R.string.request_error));
            }
        });
    }

//    最后上线时间：所有人/联系人/没有人
//    语音通话：所有人/联系人/没有人
//    电话号码：所有人/联系人/没有人
//    群组：所有人/联系人/没有人
//    消息：所有人/联系人
    @OnClick({R.id.blackLayout,R.id.lastOnlineLayout,R.id.voiceLayout,R.id.phoneLayout,R.id.groupLayout
        ,R.id.messageLayout,R.id.dontLookMeLayout,R.id.dontLookOtherLayout,R.id.lookMeScopeLayout
        ,R.id.lookOtherScopeLayout})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.blackLayout:
                BlockedUserListActivity.start(this);
                break;
            case R.id.lastOnlineLayout:
                ChooseListDialog.showChooseListDialog(this, chooseLables1, chooseSettingIndex[0], new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        settingRule(0,position);
                    }
                });
                break;
            case R.id.voiceLayout:
                ChooseListDialog.showChooseListDialog(this, chooseLables1, chooseSettingIndex[1], new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        settingRule(1,position);
                    }
                });
                break;
            case R.id.phoneLayout:
                ChooseListDialog.showChooseListDialog(this, chooseLables1, chooseSettingIndex[2], new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        settingRule(2,position);
                    }
                });
                break;
            case R.id.groupLayout:
                ChooseListDialog.showChooseListDialog(this, chooseLables2, chooseSettingIndex[3], new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        settingRule(3,position);
                    }
                });
                break;
            case R.id.messageLayout:
                ChooseListDialog.showChooseListDialog(this, chooseLables2, chooseSettingIndex[4], new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        settingRule(4,position);
                    }
                });
                break;
            case R.id.dontLookMeLayout:
                CircleSettingUserActivity.start(PrivaicyAndPermissionActivity.this,BlogPrivacyInfo.DONT_LOOK_ME);
                break;
            case R.id.dontLookOtherLayout:
                CircleSettingUserActivity.start(PrivaicyAndPermissionActivity.this,BlogPrivacyInfo.ME_DONT_LOOK);
                break;
            case R.id.lookMeScopeLayout:
                ChooseListDialog.showChooseListDialog(this, friendLookScope, friendLookMeIndex, new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        BlogPrivacyInfo info = BlogPrivacyInfo.build(BlogPrivacyInfo.FRIEND_LOOK_ME_SCOPE);
                        BlogRuleInfo ruleInfo = info.getRule();
                        if(ruleInfo!=null){
                            ruleInfo.rule = BlogRuleInfo.RULE_OF_SPECIFIC_DATE;
                            switch (position){
                                case 0:
                                    ruleInfo.days = 3;
                                    break;
                                case 1:
                                    ruleInfo.days = 30;
                                    break;
                                case 2:
                                    ruleInfo.days = 180;
                                    break;
                                case 3:
                                    ruleInfo.days = 365;
                                    break;
                            }
                        }
                        circleSetting(info);
                    }
                });
                break;
            case R.id.lookOtherScopeLayout:
                ChooseListDialog.showChooseListDialog(this, strangerLookScope, strangerLookMeIndex, new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        BlogPrivacyInfo info = BlogPrivacyInfo.build(BlogPrivacyInfo.STRANGER_LOOK_ME_SCOPE);
                        BlogRuleInfo ruleInfo = info.getRule();
                        if(ruleInfo!=null){
                            switch (position){
                                case 0:
                                    ruleInfo.rule = BlogRuleInfo.RULE_OF_SPECIFIC_NUMBER;
                                    ruleInfo.counts = 3;
                                    break;
                                case 1:
                                    ruleInfo.rule = BlogRuleInfo.RULE_OF_SPECIFIC_NUMBER;
                                    ruleInfo.counts = 10;
                                    break;
                                case 2:
                                    ruleInfo.rule = BlogRuleInfo.RULE_OF_ALL;
                                    ruleInfo.counts = 0;
                                    break;
                            }
                        }
                        circleSetting(info);
                    }
                });
                break;
        }
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_UpdateUserPrivacySettings: {
                if(tg_event.data!=null&&tg_event.data instanceof UserPrivacySettingInfo){
                    resetUI((UserPrivacySettingInfo) tg_event.data);
                }

            }
            break;
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_pricy_and_permission;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
